"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--network
Case Name   : 集群重启时，主节点网卡down
Create At   : 2021/08/02
@zou_jialiang0505328126
Description :
    1.停止集群
    2.注入网卡down故障
    3.重启集群
Expect      :
    1.成功
    2.成功
    3.失败，启动过程中，备节点无法跟主节点建立连接
History     :
    Modified by @wan005 2021/11/1:修改网卡注入时长
"""

import unittest
import time
import os
from yat.test import Node, macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class NetWork(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_root_node = Node(node='PrimaryRoot')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')

        self.log.info("-------------获取网卡名---------------")
        network_card_cmd = 'ifconfig'
        self.log.info(network_card_cmd)
        network_card_result = self.primary_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        self.log.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.primary_user_node.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                self.log.info(self.networkcard)

    def test_main(self):
        self.log.info("------------停止集群----------------")
        stop_thread = ComThread(self.primary_sh.stopDbCluster, args=())
        stop_thread.setDaemon(True)
        stop_thread.start()

        self.log.info("--------------注入网卡down故障-------------")
        time.sleep(1)
        inject_command = f"rNet_down (dev, time)" \
            f"values({self.networkcard}, 20)"
        cfe_thread = ComThread(
            self.com.cfe_inject, args=(self.primary_root_node,
                                       inject_command,))
        cfe_thread.setDaemon(True)
        cfe_thread.start()

        self.log.info("-----------------获取停止结果-------------")
        text = '----step1：停止集群 expect:成功----'
        stop_thread.join(180)
        stop_result = stop_thread.get_result()
        self.log.info(stop_result)
        result = self.primary_sh.getDbClusterStatus("status")
        self.assertTrue(stop_result and not result, '执行失败:' + text)

        self.log.info("-------------------获取故障结果---------------------")
        cfe_thread.join(180)
        result = cfe_thread.get_result()
        self.log.info(result)
        time.sleep(25)

        self.log.info("--------------注入网卡down故障-------------")
        time.sleep(1)
        inject_command = f"rNet_down (dev, time)" \
            f"values({self.networkcard}, 30)"
        cfe_thread = ComThread(
            self.com.cfe_inject, args=(self.primary_root_node,
                                       inject_command,))
        cfe_thread.setDaemon(True)
        cfe_thread.start()

        self.log.info("------------启动集群----------------")
        start_thread = ComThread(self.primary_sh.startDbCluster, args=())
        start_thread.setDaemon(True)
        start_thread.start()

        self.log.info("-----------------获取启动结果-------------")
        text = '----step2：启动集群 expect:失败----'
        start_thread.join(180)
        result = start_thread.get_result()
        self.log.info(result)
        self.assertFalse(result, '执行失败:' + text)

        self.log.info("-------------------获取故障结果---------------------")
        cfe_thread.join(180)
        result = cfe_thread.get_result()
        self.log.info(result)
        time.sleep(5)

    def tearDown(self):
        time.sleep(25)
        self.log.info("---------------启动集群------------------")
        self.primary_sh.startDbCluster()
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
